package com.thinkin.services.CRM;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;
import java.util.Map.Entry;

import org.json.JSONException;

import com.thinkin.allDo.SysDao;
import com.thinkin.services.util.BaseService;
import com.thinkin.services.util.InitSQL;
import com.thinkin.util.JsonHelper;


public class Customer {
	/**
	 * 客户资料webservice
	 */

	// public static void main(String[] args) {
	// String str = "{'keyid':'f3beddd0-6f1e-400e-9fd6-aa3c085db7eb'}";
	// // String keyid="'1'or'1'='1'";
	// Customer cus = new Customer();
	// String result = cus.DoGetPopData(str);
	// System.out.println(result);
	// }

	/**
	 * 刷新方法
	 * 
	 * @param param
	 *            传递的json格式的字符串过滤条件
	 * @return
	 */
	public String DoRefresh(String param) {
		StringBuffer str_SQL = new StringBuffer();
		// 刷新时不包含keyid就说明是概览刷新
		if (param.indexOf("keyid") == -1) {
			str_SQL.append(BuildListSQL(param));
		} else {
			str_SQL.append(BuildItemSQL(param));
		}
		String result = SysDao.getCommonServer().doQueryBatch(
				str_SQL.toString(), true);
		return result;
	}

	/**
	 * 获取概览sql
	 * 
	 * @param param
	 *            过滤条件
	 * @return 结果集的json字符串
	 */
	private String BuildListSQL(String param) {
		// 将json字符串转为键值对格式
		HashMap filter = JsonHelper.toHashMap(param);
		StringBuffer str_SQL = new StringBuffer();
		str_SQL.append("customer");
		//str_SQL.append(TiConstants.SqlSplit);
		str_SQL.append("select keyid,cusnamecn,cushelpcd,cusnameen,oldcusname,cusname,cusnature,cuslev,parentname,");
		str_SQL.append("firsigndat,aermcooptim,contact,tel,mobphone,orgcanusename,bizno,taxno,orgcodeno,industry,cusstate");
		str_SQL.append(" from e_customer where 1=1");
		Iterator keylist = filter.entrySet().iterator();
		while (keylist.hasNext()) {
			Entry entry = (Entry) keylist.next();
			if (entry.getValue().equals("")) {
				continue;
			}
			if (entry.getKey().equals("cushelpcd")) {
				str_SQL.append(String.format(
						" and nvl(cushelpcd,' ') like '%%%1$s%%'",
						entry.getValue()));
				continue;
			}
			if (entry.getKey().equals("cusname")) {
				str_SQL.append(String.format(
						" and nvl(cusname,' ') like '%%%1$s%%'",
						entry.getValue()));
				continue;
			}
			if (entry.getKey().equals("cusnamecn")) {
				str_SQL.append(String.format(
						" and nvl(cusnamecn,' ') like '%%%1$s%%'",
						entry.getValue()));
				continue;
			}
			if (entry.getKey().equals("cusstate")) {
				str_SQL.append(String.format(" and nvl(cusstate,' ')='%1$s'",
						entry.getValue()));
				continue;
			}
			if (entry.getKey().equals("cusnature")) {
				str_SQL.append(String.format(" and nvl(cusnature,' ') ='%1$s'",
						entry.getValue()));
				continue;
			}
			if (entry.getKey().equals("industry")) {
				str_SQL.append(String.format(" and nvl(industry,' ')='%1$s'",
						entry.getValue()));
				continue;
			}
			if (entry.getKey().equals("orgcanuse")) {
				str_SQL.append(String.format(" and nvl(orgcanuse='%1$s'",
						entry.getValue()));
				continue;
			}

		}
		return str_SQL.toString();
	}

	/**
	 * 获取明细界面sql，与概览分开写的目的是为了以后扩展写明细sql如：合同等
	 * 
	 * @param param
	 *            过滤条件
	 * @return 结果集的json字符串
	 */
	private String BuildItemSQL(String param) {
		// 将json字符串转为键值对格式
		HashMap filter = JsonHelper.toHashMap(param);
		StringBuffer str_SQL = new StringBuffer();
		str_SQL.append("customer");
		//str_SQL.append(TiConstants.SqlSplit);
		str_SQL.append(String.format(
				"select * from e_customer where 1=1 and keyid='%1$s'", filter
						.get("keyid").toString()));
		///根据身份获取初始化下来框数据
		//str_SQL.append(TiConstants.SqlSplit);
		str_SQL.append("attct");
		//str_SQL.append(TiConstants.SqlSplit);
		str_SQL.append(InitSQL.str_sql);
		str_SQL.append(String
				.format("select areaid as value,areaname as label from e_area join e_customer on e_customer.attpro=e_area.parentid"));
		str_SQL.append(String.format(" where e_customer.keyid='%1$s'", filter
				.get("keyid").toString()));
		//str_SQL.append(TiConstants.SqlSplit);
		///根据城市获取初始化下来框数据
		str_SQL.append("attsub");
		//str_SQL.append(TiConstants.SqlSplit);
		str_SQL.append(InitSQL.str_sql);
		str_SQL.append(String
				.format("select areaid as value,areaname as label from e_area join e_customer on e_customer.attct=e_area.parentid"));
		str_SQL.append(String.format(" where e_customer.keyid='%1$s'", filter
				.get("keyid").toString()));
		return str_SQL.toString();
	}

	/**
	 * 新增保存
	 * 
	 * @param param
	 *            json格式的字段对应字符串
	 * @return
	 */
	public String DoSaveInsert(String param) {
		String result = "";
		String isSuccess = "true";
		org.json.JSONObject jsonObject = JsonHelper.toJsonString(param);
		String keyid = UUID.randomUUID().toString();
		try {
			// 若界面没有生成keyid，则生成
			jsonObject.put("keyid", keyid);
			String datefields = jsonObject.getString("datefields");
			jsonObject.remove("datefields");
			param = jsonObject.toString();
			List<String> keys = JsonHelper.toJSONStringKey(param);
			List<Object> values = JsonHelper.toJSONStringValue(param);
			String validate = "_text";
			for (int key = 0; keys != null && keys.size() > 0
					&& key < keys.size(); key++) {
				if (keys.get(key).toString().indexOf(validate) > 0) {
					keys.remove(key);
					values.remove(key);
					--key;
				}
			}
			BaseService.doSave(keys, values, "e_customer", datefields);
			result = keyid;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			result = e.getMessage();
			isSuccess = "false";
		}
		return "{\"result\":\"" + result + "\",\"isSuccess\":\"" + isSuccess
				+ "\"}";
	}

	/**
	 * 修改保存
	 * 
	 * @param param
	 * @return
	 */
	public String DoSaveEdit(String param) {
		String result = "";
		String isSuccess = "true";
		org.json.JSONObject jsonObject = JsonHelper.toJsonString(param);
		try {
			String datefields = jsonObject.getString("datefields");
			jsonObject.remove("datefields");
			param = jsonObject.toString();
			List<String> keys = JsonHelper.toJSONStringKey(param);
			List<Object> values = JsonHelper.toJSONStringValue(param);
			String validate = "_text";
			for (int key = 0; keys != null && keys.size() > 0
					&& key < keys.size(); key++) {
				if (keys.get(key).toString().indexOf(validate) > 0) {
					keys.remove(key);
					values.remove(key);
					--key;
				}
			}
			result = BaseService.doEdit(keys, values, "e_customer", datefields);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			// e.printStackTrace();
			isSuccess = "false";
			result = e.getMessage();
		}
		return "{\"result\":\"" + result + "\",\"isSuccess\":\"" + isSuccess
				+ "\"}";
	}

	/**
	 * 删除方法
	 * 
	 * @param param
	 * @return
	 */
	public String DoDelete(String param) {
		String result = "";
		List<Object> values = JsonHelper.toJSONStringValue(param);
		String str_delSQL = String
				.format("delete from e_customer where keyid=?");
		try {
			result = SysDao.getCommonServer().doDelete(str_delSQL,
					values.toArray(), true);
		} catch (Exception e) {
			result = e.getMessage();
		}
		return result;
	}

	/**
	 * 获取挑选框数据
	 * 
	 * @param param
	 *            传递的json格式的字符串过滤条件
	 * @return
	 */
	public String DoGetPopData(String param) {
		StringBuffer str_SQL = new StringBuffer();
		str_SQL.append(BuildPopSQL(param));
		String result = SysDao.getCommonServer().doQueryBatch(
				str_SQL.toString(), true);
		return result;
	}

	/**
	 * 拼接PopSQL
	 * 
	 * @param param
	 * @return
	 */
	private String BuildPopSQL(String param) {
		// 将json字符串转为键值对格式
		HashMap filter = JsonHelper.toHashMap(param);
		StringBuffer str_SQL = new StringBuffer();
		str_SQL.append("customer");
		//str_SQL.append(TiConstants.SqlSplit);
		str_SQL.append("select e_customer.keyid,e_customer.cusnamecn, e_customer.cuscd,e_customer.cushelpcd,e_customer.cusnameen,");
		str_SQL.append("e_customer.cusname,e_customer.cusnature,e_customer.cuslev,e_customer.parentname,e_customer.firsigndat,e_customer.aermcooptim,");
		str_SQL.append("e_customer.contact,e_customer.tel,e_customer.mobphone,e_customer.orgcanusename,e_customer.bizno,e_customer.taxno,");
		str_SQL.append("e_customer.orgcodeno,e_customer.industry,e_customer.cusstate,e_customer.cusattribute");
		str_SQL.append(" from e_customer where 1=1 and nvl(e_customer. cusstate, ' ')<> '停用'");
		Iterator keylist = filter.entrySet().iterator();
		while (keylist.hasNext()) {
			Entry entry = (Entry) keylist.next();
			if (entry.getValue().equals("") || entry.getValue().equals(" ")) {
				continue;
			}
			if (entry.getKey().equals("cushelpcd")) {
				str_SQL.append(String.format(
						" and nvl(cushelpcd,' ') like '%%%1$s%%'",
						entry.getValue()));
				continue;
			}
			if (entry.getKey().equals("cusname")) {
				str_SQL.append(String.format(
						" and nvl(cusname,' ') like '%%%1$s%%'",
						entry.getValue()));
				continue;
			}
			if (entry.getKey().equals("cusnamecn")) {
				str_SQL.append(String.format(
						" and nvl(cusnamecn,' ') like '%%%1$s%%'",
						entry.getValue()));
				continue;
			}
			if (entry.getKey().equals("cusattribute")) {
				str_SQL.append(String
						.format(" and upper(e_customer.cusattribute) like upper('%%<%1$s>%%')",
								entry.getValue()));
				continue;
			}

		}
		return str_SQL.toString();
	}
}
